package cn.yuanqiao.archive.bianjifabu.util;

import cn.yuanqiao.archive.bianjifabu.domain.Yqfanganwater;
import cn.yuanqiao.archive.management.utils.StringUtils;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfStamper;
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;

import javax.swing.*;
import java.awt.*;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * @author zjj
 * @date 2023/5/19
 */
public class PdfUtils {
    /**
     * 合并pdf
     * @param files 需要合并的pdf路径
     * @param newfile 合并成新的文件的路径
     */
    public static boolean mergePdfFiles(String[] files, String newfile) {
        boolean retValue = false;
        Document document = null;
        PdfCopy copy = null;
        PdfReader reader = null;
        try {
            document = new Document(new PdfReader(files[0]).getPageSize(1));
            copy = new PdfCopy(document, new FileOutputStream(newfile));
            document.open();
            for (int i = 0; i < files.length; i++) {
                reader = new PdfReader(files[i]);
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
                reader.close();
            }
            retValue = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (copy != null) {
                copy.close();
            }
            if (document != null) {
                document.close();
            }
        }
        return retValue;
    }



    /**
     * 给PDF添加水印  D:\\source\\simsun.ttc,0
     * @param inputFile 原文件路径+名称
     * @param outputFile 添加水印后输出文件保存的路径+名称
     * @param
     */
    public static void PDFAddWatermark(String inputFile, String outputFile, Yqfanganwater yqfanganwater) {
        //内容为必填
        String waterneirong = yqfanganwater.getWaterNeirong();
        String gaodu = yqfanganwater.getGaodu();
        String kuandu = yqfanganwater.getKuandu();
        String jiange = yqfanganwater.getJiange();
        String toumingdu = yqfanganwater.getToumingdu();
        String qingxiedu = yqfanganwater.getQingxiedu();
        String zitidaxiao = yqfanganwater.getZitiDaxiao();
        // 水印的高和宽（参数可调节）
        int textH = 75;
        int textW = 170;
        // 间隔距离（参数可调节）
        int interval = 30;
        float ca = 0.2f;
        float rotation = 30;
        float fontSize = 20;
        if(!StringUtils.isNULL(gaodu)) textH = Integer.valueOf(gaodu);
        if(!StringUtils.isNULL(kuandu)) textW = Integer.valueOf(kuandu);
        if(!StringUtils.isNULL(jiange)){
            if(jiange.startsWith("0.")){
                interval = jiange.charAt(2);
            }else{
                interval = Integer.valueOf(jiange);
            }
        }
        if(!StringUtils.isNULL(toumingdu)) ca = Float.valueOf(toumingdu);
        if(!StringUtils.isNULL(qingxiedu)) rotation = Float.valueOf(qingxiedu);
        if(!StringUtils.isNULL(zitidaxiao)) fontSize = Float.valueOf(zitidaxiao);

        try {
            com.itextpdf.text.pdf.PdfReader reader = new com.itextpdf.text.pdf.PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            //String fontPosition = SystemConfig.getParamValueByCode("FABUWATERFONTPOSITION");
            //if(!fontPosition.endsWith("/")) fontPosition+="/";
            ClassPathResource classPathResource = new ClassPathResource("Fonts/simsun.ttc");
            // 读取文件流
            InputStream inputStream = classPathResource.getInputStream();
            byte[] bytes = IOUtils.toByteArray(inputStream);
            BaseFont base = BaseFont.createFont("simsun.ttc,0", BaseFont.IDENTITY_H, false,true,bytes,null);

            PdfGState gs = new PdfGState();
            gs.setFillOpacity(ca);//改透明度
            gs.setStrokeOpacity(0.4f);
            int total = reader.getNumberOfPages() + 1;
            JLabel label = new JLabel();
            label.setText(waterneirong);
            PdfContentByte under;
            // 可添加多个水印
            Rectangle pageRect = null;
            FontMetrics metrics;
            label.setText(waterneirong);
            metrics = label.getFontMetrics(label.getFont());
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                // 在内容上方加水印
                under = stamper.getOverContent(i);
                // 在内容下方加水印
                //under = stamper.getUnderContent(i);
                under.saveState();
                under.setGState(gs);
                under.beginText();
                //under.setFontAndSize(base, 20);
                under.setFontAndSize(base, fontSize);
                // 水印文字成30度角倾斜
                for (int height = interval + textH; height < pageRect.getHeight();
                     height = height + textH * 3) {
                    for (int width = interval + textW; width < pageRect.getWidth() + textW;
                         width = width + textW * 2) {
                        under.showTextAligned(Element.ALIGN_LEFT
                                , waterneirong, width - textW,
                                height - textH, rotation);
                    }
                }
                // 添加水印文字
                under.endText();
            }
            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String a = "hello";
        System.out.println(a.charAt(4));
    }
}
